/**
 *   Created by lihao on  2017/10/30
 */
    'use strict';

 let request = require('request');
 let baseConfig = require('../resource/base-config');
 module.exports = distributionService;


// 声明分发对象
function distributionService() {}

/**
 * get请求
 *  @params  callback   function(result){ res.send({success:false,message:'请求异常'}) }   错误的回调函数
 */
distributionService.get = function(req, res, callback){
                    let url = req.query.url;
                    let spliteUrl  = url.split('?');
                    let query = '?';
                    if(spliteUrl.length > 1){
                        query += spliteUrl[1];
                    }
                    get(spliteUrl[0], query, req, callback);
};

//post请求
distributionService.post = function(req, res, callback){
                    post(req.query.url, req, callback);
};

distributionService.index = function(req,res,callback){
                    post('/index',req, callback);
};

/*
 * get request
 *  @params  queryString
 *  @params  req
 *  @params  callback
 */
function get(url, queryString, req, callback){
    let host = req.query.host;
    request.get({
        qs: parseUrlParams(queryString),
        json: true,
        url: baseConfig[host] + url
    },function(err,res,body){
        if(!err && res.statusCode === 200){
            if(callback){
                callback(body);
            }
        } else {
            callback({success:false,message:'请求异常'})
        }
    });

    //解析url
    function parseUrlParams(url){
        url = url.replace(/\?/gi,'');
        let urlArray = url.split('&');
        let params = {};
        for(let i=0; i<urlArray.length; i++){
            let item = urlArray[i];
            let itemArray = item.split("=");
            params[itemArray[0]] = itemArray[1];
        }
        return params;
    }
}

/*
 * post request
 *  @param url
 *  @param req
 *  @param callback
 *
 */
function post(url, req, callback) {
    let host = req.query.host;
    request.post({
        json: true,
        url: (baseConfig[host]) + url,
        form: req.body
    },function(err, res, body){
        if(!err && res.statusCode === 200){
            let result = body;
            callback(result);
        } else {
            callback({success: false, message: '请求异常'})
        }
    });
}
